package com.jt.deepSeaMain;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.jt.config.TimingConfig;
import com.jt.dto.CollectParamsDto;
import com.jt.mapper.TimingMapper;
import com.jt.pojo.*;
import com.jt.service.CarService;
import com.mysql.cj.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

@Component
@Slf4j
public class DeepCarTaskService extends TimingConfig {


    @Value("${task.car.switch}")
    private Boolean carSwitch;

    @Value("${task.car.cron}")
    private String carCron;

    @Value("${task.car.startTime}")
    private String startTime;


    @Autowired
    private TimingMapper timingMapper;


    @Autowired
    private HttpURLConnectionGetResult httpURLConnectionGetResult;



    private CarService carService;


    @Override
    protected Boolean getSwitch() {
        return carSwitch;
    }

    @Override
    protected String getCron() {
        return carCron;
    }

    @Override
    protected void processTask() throws IOException {
        try {
            log.info("<<<<<<<<<<<<<<<<<start车脸定时任务>>>>>>>");
            //2:车辆car
            CollectParamsDto collectParamsDtoCar = new CollectParamsDto();
            collectParamsDtoCar.setPage(1);
            collectParamsDtoCar.setPageSize(100);
            collectParamsDtoCar.setSourceId("10174,7115");
            collectParamsDtoCar.setTargetType("car");
            collectParamsDtoCar.setRelative("face");
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String systemTime = sdf.format(new Date());
            if (systemTime.compareTo(startTime) < 0) {
                log.error("车辆定时器执行时间小于系统默认开始时间");
                throw new RuntimeException("车辆定时器执行时间小于系统默认开始时间");
            } else {
                getCarCollectListAndSaveAll(startTime, systemTime, collectParamsDtoCar);
            }
        } catch (Exception e) {
            log.error(e.toString());
        }
    }

    /*统一去存入定时任务的开始结束和状态以及人抓入库和定时器时间入库*/
    public void getCarCollectListAndSaveAll(String startTime, String systemTime, CollectParamsDto collectParamsDtoCar) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<People> peopleList = null;
        List<String> timeList = new ArrayList<>();
        /*结束时间，拿到系统前一分钟时间*/
        String beforeTime = getCarBeForTime(systemTime);
        try {
            /*如果定时表中没有数据，是第一次查，我们就取全局设定的开始时间,反之取最后查出来的时间*/
            Timing timingOne = timingMapper.selectOne(new QueryWrapper<Timing>().eq("type", "face").orderByDesc("end_time").last("limit 1"));
            Timing timing = new Timing();
            timing.setId(UUID.randomUUID().toString().substring(10));
            timing.setType("face");
            timing.setState("0");
            if (Objects.isNull(timingOne)) {
                /*定时任务开始之前存库一次*/
                timing.setStartTime(startTime);
                timing.setEndTime(beforeTime);
                timingMapper.insert(timing);/*0执行中，1异常,2完成*/
                timeList.add(startTime);
                timeList.add(beforeTime);
                collectParamsDtoCar.setTimeList(timeList);
                /*调用采集接口*/
                retrieveCollect(collectParamsDtoCar, timing);
            } else {
                /*定时任务开始之前存库一次*/
                String endTime = timingOne.getEndTime();
                timing.setStartTime(endTime);
                timing.setEndTime(beforeTime);
                timingMapper.insert(timing);/*0执行中，1异常,2完成*/
                timeList.add(endTime);
                timeList.add(beforeTime);
                collectParamsDtoCar.setTimeList(timeList);
                /*调用采集接口*/
                retrieveCollect(collectParamsDtoCar, timing);
            }
        } catch (Exception e) {
            log.error(e.toString());
        }

    }

    public void retrieveCollect(CollectParamsDto collectParamsDtoFace, Timing timing) {
        List<People> peopleList = null;
        CollectParamsDto collectParamsDto = new CollectParamsDto();
        List<CollectPeopleAndPeoplePass> collectPeopleAndPeoplePasses = null;
        try {
            boolean isAndNo = true;
            String jsonStr = "";
            while (isAndNo) {
                if (StringUtils.isNullOrEmpty(jsonStr)) {
                    /*测试调用自己的接口*/
//                    String ceShiString = httpURLConnectionGetResult.ceShiCollectList();
//                    JSONObject jsonObject = JSONObject.parseObject(ceShiString);
//                    String respCode = jsonObject.getString("respCode");
//                    System.out.println("测试调用自己的接口 respCode=="+respCode);
                    /*第一次请求*/
                    jsonStr = httpURLConnectionGetResult.getCollectList(collectParamsDtoFace);
                    System.out.println("第一次请求采集数据结果====={}" + jsonStr);
                } else {
                    /*不是第一次访问*/
                    JSONObject jsonObject = JSON.parseObject(jsonStr);
                    String dataString = jsonObject.get("data").toString();
                    JSONObject jsonObjectResult = JSONObject.parseObject(dataString);
                    String partitionId = jsonObjectResult.get("partitionId").toString();
                    String sequence = jsonObjectResult.get("sequence").toString();
                    log.info("不是第一次请求，请求参数partitionId={},sequence={}", partitionId, sequence);
                    collectParamsDto.setPartitionId(partitionId);
                    collectParamsDto.setSequence(sequence);
                    collectParamsDto.setSourceId(collectParamsDtoFace.getSourceId());
                    collectParamsDto.setTargetType(collectParamsDtoFace.getTargetType());
                    collectParamsDto.setTimeList(collectParamsDtoFace.getTimeList());
                    collectParamsDto.setPageSize(collectParamsDtoFace.getPageSize());
                    collectParamsDto.setRelative(collectParamsDtoFace.getRelative());
                    log.info("collectParamsDto不是第一次调用时的入参值==={}", collectParamsDto);
                    jsonStr = httpURLConnectionGetResult.getCollectList(collectParamsDto);
                    System.out.println("非第一次请求采集数据结果====={}" + jsonStr);
                }

                JSONObject jsonObject = JSON.parseObject(jsonStr);
                String code = jsonObject.get("code").toString();
                List<Car> peopleListAll = new ArrayList<>();
                if (code.equals("200")) {
                    System.out.println("进来了等于200>>>>>>>");
                    /*保存结果*/
                    String dataStr = jsonObject.getString("data");
                    JSONObject jsonObjectData = JSONObject.parseObject(dataStr);
                    String dataString = jsonObjectData.getString("data");
                    JSONArray jsonArray = JSONObject.parseArray(dataString);
                    log.info("转化成jsonArray成功????????{}", jsonArray.size());
                    if (jsonArray.size() > 0) {
                        for (int i = 0; i < jsonArray.size(); i++) {
                            /*拿到data中每个对象*/
                            JSONObject jsonObjectOne = jsonArray.getJSONObject(i);
                            String faces = jsonObjectOne.getString("faces");
                            JSONArray jsonArrayFaceArry = JSONObject.parseArray(faces);
                            for (int j = 0; j < jsonArrayFaceArry.size(); j++) {
                                People people = jsonArrayFaceArry.getJSONObject(j).toJavaObject(People.class);
                                String bodies = jsonObjectOne.getString("bodies");
                                JSONArray jsonArrayBodiesArray = JSONObject.parseArray(bodies);
                                if (jsonArrayBodiesArray.size() > 0) {
                                    for (int k = 0; k < jsonArrayBodiesArray.size(); k++) {
                                        PeoplePass peoplePass = jsonArrayBodiesArray.getJSONObject(k).toJavaObject(PeoplePass.class);
                                        log.info("peoplePass===????????{}", peoplePass);
                                        people.setPeopleId(UUID.randomUUID().toString().substring(8));
                                        people.setCoatStyle(peoplePass.getCoatStyle());
                                        people.setCoatPattern(peoplePass.getCoatPattern());
                                        people.setCoatColor(peoplePass.getCoatColor());
                                        people.setPantsColor(peoplePass.getPantsColor());
                                        people.setPantsStyle(peoplePass.getPantsStyle());
                                        people.setPantsPattern(peoplePass.getPantsPattern());
                                        people.setSinglebag(peoplePass.getSinglebag());
                                        people.setBackbag(peoplePass.getBackbag());
                                        people.setRide(peoplePass.getRide());
                                        people.setHandbag(peoplePass.getHandbag());
                                        people.setHasCoat(peoplePass.getHasCoat());
                                        people.setPeoplePassId(peoplePass.getId());
                                        people.setPeoplePassSmallUrl(peoplePass.getSmallUrl());
                                    }
                                }
                                String cars = jsonObjectOne.getString("cars");
                                JSONArray jsonArrayCarsArray = JSONObject.parseArray(cars);
                                if (jsonArrayCarsArray.size() > 0) {
                                    for (int h = 0; h < jsonArrayCarsArray.size(); h++) {
                                        Car car = jsonArrayCarsArray.getJSONObject(h).toJavaObject(Car.class);
                                        people.setCarBrand(car.getBrand());
                                        people.setCarColor(car.getColor());
                                        people.setCarBrandCode(car.getBrandCode());
                                        people.setCarPlateNumber(car.getPlateNumber());
                                        people.setCarType(car.getType());
                                        people.setCarPlateColor(car.getPlateColor());
                                        people.setCarId(car.getId());
                                        people.setCarSmallUrl(car.getSmallUrl());
                                    }
                                }
                                /*存图片*/
                                String id = people.getId();
                                //人大图
                                String bigUrl = people.getBigUrl();
                                //人小图
                                String smallUrl = people.getSmallUrl();
                                //人体图
                                String peoplePassSmallUrl = people.getPeoplePassSmallUrl();
                                //车小图
                                String carSmallUrl = people.getCarSmallUrl();
//                                httpURLConnectionGetResult.postUrls(id, bigUrl, smallUrl, peoplePassSmallUrl, carSmallUrl);
                                peopleListAll.add(null);
                            }
                        }
                    } else {
                        log.info("data转化为list长度为0");
                    }
                    /*保存人脸和关联人体和车辆数据数据*/
                    if (!CollectionUtils.isEmpty(peopleListAll)) {
                        boolean b = carService.saveBatch(peopleListAll);
                        if (b) {
                            log.info("人脸{}条数据存库成功", peopleListAll.size());
                        } else {
                            log.error("保存人脸和关联人体和车辆数据存库失败");
                        }
                    }
                    /*拿到数据的长度*/
                    if (jsonArray.size() < collectParamsDtoFace.getPageSize()) {
                        /*如果小于则说明已经查完了*/
                        UpdateWrapper<Timing> wrapper = new UpdateWrapper<>();
                        wrapper.eq("id", timing.getId());
                        Timing timingNew = new Timing();
                        if (!StringUtils.isNullOrEmpty(collectParamsDto.getPartitionId())) {
                            timingNew.setPartitionId(collectParamsDto.getPartitionId());
                        }
                        if (!StringUtils.isNullOrEmpty(collectParamsDto.getSequence())) {
                            timingNew.setSequence(collectParamsDto.getSequence());
                        }
                        timingNew.setState("1");
                        timingMapper.update(timingNew, wrapper);
                        log.info("完成");
                        break;
                    } else {
                        /*在进行中*/
                        UpdateWrapper<Timing> wrapper = new UpdateWrapper<>();
                        wrapper.eq("id", timing.getId());
                        Timing timingNew = new Timing();
                        if (!StringUtils.isNullOrEmpty(collectParamsDto.getPartitionId())) {
                            timingNew.setPartitionId(collectParamsDto.getPartitionId());
                        }
                        if (!StringUtils.isNullOrEmpty(collectParamsDto.getSequence())) {
                            timingNew.setSequence(collectParamsDto.getSequence());
                        }
                        timingNew.setState("0");
                        log.info("进行中");
                        timingMapper.update(timingNew, wrapper);
                    }
                } else {
                    /*失败了*/
                    UpdateWrapper<Timing> wrapper = new UpdateWrapper<>();
                    wrapper.eq("id", timing.getId());
                    Timing timingNew = new Timing();
                    if (!StringUtils.isNullOrEmpty(collectParamsDto.getPartitionId())) {
                        timingNew.setPartitionId(collectParamsDto.getPartitionId());
                    }
                    if (!StringUtils.isNullOrEmpty(collectParamsDto.getSequence())) {
                        timingNew.setSequence(collectParamsDto.getSequence());
                    }
                    timingNew.setState("2");
                    timingMapper.update(timingNew, wrapper);
                    log.error("采集接口连环调用失败了");
                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public String getCarBeForTime(String systemTime) {
        String resultTime = "";
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            // 将传入进来的时间转化为"yyyy-MM-dd HH:mm:ss"格式（格式可根据实际情况更改）
            Date startTime = sdf.parse(systemTime);
            System.out.println("系统时间==" + systemTime);
            // 将传入进来的时间转化为时间戳 ，然后再当前时间戳上减60000ms（1min=60000ms）
            long endTimeStamp = startTime.getTime() - 60000 * 2;
            // 转化计算得到的时间戳
            String endDateTemp = sdf.format(endTimeStamp);
            Date endTime = sdf.parse(endDateTemp);
            resultTime = sdf.format(endTime);
        } catch (Exception e) {
            log.error("获取系统前一分钟时间异常");
            e.printStackTrace();
        }
        return resultTime;
    }
}
